<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="水表号" prop="s_water_meter_code" style="width: 240px;">
          <el-input v-model="queryParams.s_water_meter_code" placeholder="水表号" clearable />
        </el-form-item>
        <el-form-item label="抄表员id" prop="meter_reader_id" style="width: 240px;">
          <el-input v-model="queryParams.meter_reader_id" placeholder="抄表员id" clearable />
        </el-form-item>
        <el-form-item label="抄表员姓名" prop="s_meter_reader_name" style="width: 240px;">
          <el-input v-model="queryParams.s_meter_reader_name" placeholder="抄表员姓名" clearable />
        </el-form-item>
        <el-form-item label="是否结清" prop="settle_status" style="width: 240px;">
          <el-select v-model="queryParams.settle_status" placeholder="全部" clearable class="!w-[180px]">
            <el-option label="结清" :value="1" />
            <el-option label="未结清" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可用" prop="valid_status" style="width: 240px;">
          <el-select v-model="queryParams.valid_status" placeholder="全部" clearable class="!w-[180px]">
            <el-option label="正常" :value="1" />
            <el-option label="作废" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker v-model="queryParams.month" value-format="YYYYMM" format="YYYY-MM" type="month"
            placeholder="月份" />
        </el-form-item>
        <el-form-item label="创建时间" prop="date">
          <el-date-picker v-model="date" value-format="x" type="datetimerange" :default-time="defaultTime2"
            range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
          <exportFile type="water_meter_bill" :data="queryParams"></exportFile>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div></div>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row>
        <el-table-column label="水表id" prop="id" width="80" />
        <el-table-column label="水表编号" prop="water_meter_code" width="100" />
        <el-table-column label="户主姓名" prop="water_meter.holder_username" min-width="150" />
        <el-table-column label="抄表员姓名" prop="meter_reader_name" min-width="120" />
        <el-table-column label="月份" prop="month" min-width="80" />
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <span>{{ scope.row?.valid_status == 1 ? '正常' : '已作废' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否结清" min-width="100">
          <template #default="scope">
            <span>{{ scope.row?.settle_status == 1 ? '已结清' : '未结清' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用水量(m³)" prop="consumption" min-width="140" />
        <el-table-column label="上次读数" prop="last_number" min-width="140" />
        <el-table-column label="此次读数" prop="new_number" min-width="140" />
        <el-table-column label="费用金额" prop="need_pay_amount" min-width="160" />
        <el-table-column align="center" fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button v-if="scope.row?.valid_status == 1" v-hasPerm="'waterMeter:monthlyBill:receipt'" type="primary"
              size="small" link icon="Document" @click="handleisShow(scope.row)">
              收据
            </el-button>
            <el-button v-if="Number(scope.row?.late_fee) > 0" v-hasPerm="'/admin/water/waterMeterBill/clearLateFee'"
              type="danger" size="small" link icon="delete" @click="handleClearLateFee(scope.row)">
              清滞纳金
            </el-button>
            <el-button v-hasPerm="'/admin/water/waterMeterBalanceLog/pageList'" type="primary" size="small" link
              icon="Document" @click="handleOpenList(scope.row)">
              费用明细
            </el-button>
            <el-button v-hasPerm="'/admin/water/waterMeterBill/wasted'" v-if="scope.row?.valid_status == 1"
              @click="handleWaterMeterBill(scope.row.id)" type="primary" size="small" link icon="edit">
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <el-dialog :close-on-click-modal="false" v-model="listShow" title="费用明细" append-to-body width="70%"
      @close="handleCloseList">
      <el-table ref="dataTableRef" :data="logList" highlight-current-row>
        <el-table-column label="计算用水量" prop="used" width="120" />
        <el-table-column label="最终费用" prop="final_fee" width="120" />
        <el-table-column label="城市供水运营水费" prop="urban_fee" width="160" />
        <el-table-column label="水资源费" prop="resource_fee" width="120" />
        <el-table-column label="水利工程运营水费" prop="conservancy_fee" width="160" />
        <el-table-column label="污水处理费" prop="sewage_treat_fee" width="120" />
        <el-table-column label="用水文字说明" prop="name" />
      </el-table>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" style="background-color: #edf3f9 !important;" v-model="isShow" title="收据"
      append-to-body width="900px" @close="handleClose" top="1%">
      <img :src="imageUrl" class="imageUrl" width="860px" height="560px" alt="">
      <div ref="card" class="p-3 card bg-[#FFF]">
        <div class="shoubox">
          <div class="text-box">
            <div>第一联 存根(白)</div>
            <div class="mt-4">第二联 客户(红)</div>
          </div>
          <div class="border-[#000]">
            <div class="text-center text-[24px]">
              <span class="border-b-1">{{ rush_title }}</span>
            </div>
            <div class="flex mt-5 mb-1 justify-between">
              <div class="flex-1">抢修电话：{{ rush_tel }}</div>
              <div class="flex-1 text-center">时间：{{ formatTimestamp(rowData.created_at * 1000) }}</div>
              <div class="flex-1 text-right">No：{{ rowData?.id?.toString().padStart(7, '0') }}</div>
            </div>
            <el-table :resizable="false" :data="tableData" :span-method="objectSpanMethod" border style="width: 100%;">
              <el-table-column
                :label="`户主：${rowData?.water_meter?.holder_username}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;水表编号：${rowData?.water_meter_code}`">
                <el-table-column prop="remack" label="\" width="1" />
                <el-table-column prop="text" label="\" width="1" />
                <el-table-column prop="last_number" label="起 度" align="center" />
                <el-table-column prop="new_number" label="止 度" align="center" />
                <!-- <el-table-column prop="sewage_treat_fee" label="代收排污费" width="120" align="center" /> -->
                <el-table-column prop="amount_name" label="收费类别" align="center" width="100" />
                <el-table-column v-if="rowData.charge_mode == 2" prop="stage_no" width="60" label="阶梯" align="center" />
                <el-table-column prop="used" label="用 量" align="center" />
                <el-table-column prop="unit" label="单 价" align="center" />
                <el-table-column label="金 额" prop="total" align="center">
                  <el-table-column prop="wan" label="万" width="40" align="center" />
                  <el-table-column prop="qian" label="千" width="40" align="center" />
                  <el-table-column prop="bai" label="百" width="40" align="center" />
                  <el-table-column prop="shi" label="十" width="40" align="center" />
                  <el-table-column prop="yuan" label="元" width="40" align="center" />
                  <el-table-column prop="jiao" label="角" width="40" align="center" />
                  <el-table-column prop="fen" label="分" width="40" align="center" />
                </el-table-column>
              </el-table-column>
            </el-table>
            <div class="flex border-b  border-r border-[#000000]">
              <div class="w-[235px] p-2 text-center border-r border-l border-[#000]">合计金额（大写）</div>
              <div class="p-2 flex">
                <div class="w-[400px] flex items-center">
                  <img class="w-[18px] h-[18px] mr-1" src="@/assets/images/cuo.png" alt="">
                  {{ numberConver(Number(rowData.need_pay_amount)) }}
                </div>
                <div>(小写) ￥{{ rowData.need_pay_amount }}</div>
              </div>
            </div>
          </div>
          <div class="reamck">
            <div class="reamck-text">备 注</div>
            <div class="input-box">
              <el-input v-model="inputText3" type="textarea" class="no-border-input w-[100%]" placeholder="备注,点击可编辑" />
            </div>
          </div>
        </div>
        <div class="flex justify-between mt-1">
          <div class="flex items-center flex-1 select-box">
            <div class="w-[70px]">收款人：</div>
            <table-select v-if="isShow" class="!w-[100%]" :text="userData" :select-config="meterReader"
              @confirmClear="handleUserClear" @confirm-click="handleUserConfirm">
            </table-select>
            <div class="select"></div>
          </div>

          <div>开票人：<el-input v-model="inputText2" class="no-border-input" style="width: 220px;border: none;"
              placeholder="开票人,点击可编辑" /></div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="qrcodeLoading" type="primary" @click="handlePrint">打 印</el-button>
          <el-button :loading="qrcodeLoading" type="primary" @click="handleSubmitQrCode">下 载</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MonthlyBill",
  inheritAttrs: false,
});

import accountAPI from "@/api/waterMeter/accountAdmin";
import monthlyBillAPI, { PageVO, monthlyBillPageQuery } from "@/api/waterMeter/monthlyBill";
import exportFile from '@/components/exportFile/index.vue';
import { useUserStore } from "@/store";
import { convertToMoneyArray, formatTimestamp, numberConver } from '@/utils/index';
import { ElMessage } from "element-plus";
import html2canvas from 'html2canvas';
import meterReader from "./config/meterReader";
const userStore = useUserStore();

// 用户回显
const userRow = ref<any>("");
const handleUserConfirm = (data: any[]) => {
  userRow.value = data[0];
  inputText.value = data[0].name;
}

const defaultTime2: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
] // '00:00:00', '23:59:59'


const userData = computed(() => {
  if (userRow.value !== "") {
    return userRow.value
      ? `${userRow.value.name}`
      : "";
  }
});

// 清空
const handleUserClear = () => {
  userRow.value = "";
  inputText.value = "";
}

const queryFormRef = ref(ElForm);
const pageData = ref<PageVO[]>([]);
const loading = ref(false);
const total = ref(0);
const listShow = ref(false);
const logList = ref<any>([]);
const inputText = ref("");
const inputText2 = ref("");
const inputText3 = ref("");

// 收据
const isShow = ref(false);
const rush_title = ref("成都市武侯区机投自来水经营服务站水费收款凭据");
const rush_tel = ref("87481166");
const rowData = ref<any>({});
const qrcodeLoading = ref(false);
const card = ref<any>(null)

// 下载收据
const handleSubmitQrCode = () => {
  if (inputText.value == "") {
    ElMessage.warning('请输入收款人');
    return;
  }

  if (inputText2.value == "") {
    ElMessage.warning('请输入开票人');
    return;
  }


  qrcodeLoading.value = true;
  if (card.value) {
    html2canvas(card.value).then((canvas) => {
      // 将canvas转化为图片并下载
      const link = document.createElement('a')
      link.href = canvas.toDataURL('image/png')
      link.download = `${Date.now()}.png`
      link.click()
      qrcodeLoading.value = false;
      inputText.value = "";
      inputText2.value = "";
      inputText3.value = "";
    })
  }
}

const handlePrint = () => {
  if (inputText.value == "") {
    ElMessage.warning('请输入收款人');
    return;
  }

  if (inputText2.value == "") {
    ElMessage.warning('请输入开票人');
    return;
  }

  html2canvas(card.value).then((canvas) => {
    // 将canvas转化为图片并下载
    imageUrl.value = canvas.toDataURL();

    if (imageUrl.value) {
      // 打开一个新的打印窗口
      setTimeout(() => {
        const printWindow: any = window.open('', '', 'width=1000,height=800');
        // 将生成的图片插入到打印窗口
        printWindow.document.write('<html><head><title>打印截图</title></head><body>');
        printWindow.document.write('<img src="' + imageUrl.value + '" style="width:860px; height:560px;">');
        printWindow.document.write('</body></html>');
        printWindow.document.close();

        // 等待窗口加载完成后触发打印
        printWindow.print();
      })
    }
  })

}

// 获取联系电话
accountAPI.getMultiGet({
  codes: 'service_tel'
}).then((res: any) => {
  rush_tel.value = res.lists.service_tel;
})

// 关闭弹窗
const handleClose = () => {
  tableData.value = [];
  isShow.value = false;
  inputText.value = "";
  inputText2.value = "";
  inputText3.value = "";
  handleUserClear();
}

const tableData = ref<any>([])

// 换行规则
let objectSpanMethod: any = "";
let imageUrl = ref("");
const handleisShow = (row: any) => {
  isShow.value = true;
  rowData.value = row;
  inputText2.value = userStore.userInfo.info.nickname;

  // 总价
  let total = 0;
  let result = ref<any>([]);

  row.amount_details.forEach((n: any, i: number) => {
    let p = convertToMoneyArray(Number(n.urban_fee) + Number(n.conservancy_fee) + Number(n.resource_fee));
    let w = convertToMoneyArray(Number(n.sewage_treat_fee));
    result.value.push({
      last_number: '',
      new_number: '',
      consumption: '',
      amount_name: n.name,
      // sewage_treat_fee: n.sewage_treat_fee,
      used: n.used,
      final_fee: n.final_fee,
      stage_no: n.stage_no,
      unit: Number(Number(n.urban_price) + Number(n.conservancy_price) + Number(n.resource_price)).toFixed(2),
      wan: p[0],
      qian: p[1],
      bai: p[2],
      shi: p[3],
      yuan: p[4],
      jiao: p[5],
      fen: p[6],
    })

    result.value.push({
      last_number: '',
      new_number: '',
      consumption: '',
      amount_name: '污水处理费',
      // sewage_treat_fee: n.sewage_treat_fee,
      used: '',
      final_fee: n.final_fee,
      stage_no: n.stage_no,
      unit: Number(Number(n.sewage_treat_price)).toFixed(2),
      wan: w[0],
      qian: w[1],
      bai: w[2],
      shi: w[3],
      yuan: w[4],
      jiao: w[5],
      fen: w[6],
    })
    result.value[0].last_number = row.last_number;
    result.value[0].new_number = row.new_number;
    result.value[0].consumption = row.consumption;

    // 总价
    total += Number(n.final_fee);
    setTimeout(() => {
      if (card.value) {
        html2canvas(card.value).then((canvas) => {
          // 将canvas转化为图片并下载
          imageUrl.value = canvas.toDataURL();
        })
      }
    }, 0);
  });
  ;

  tableData.value.splice(0, result.value.length, ...result.value);

  objectSpanMethod = ({
    rowIndex,
    columnIndex,
  }: any) => {
    if (rowIndex === result.value.length) {
      if (columnIndex === 0) {
        return [1, 7]
      }
    } else if (rowIndex === result.value.length + 1) {
      if (columnIndex === 0) {
        return [1, 16]
      }
    }
  }
};

const handleClearLateFee = (row: any) => {
  ElMessageBox.confirm("该账单的滞纳金金额将清零，并且不再计算滞纳金，该操作不可逆，请确认操作?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    monthlyBillAPI.clearLateFee({ id: row.id }).then(res => {
      ElMessage.success("删除成功");
      handleResetQuery();
    })
  }, () => {
    ElMessage.info("已取消删除");
  }
  );
}

// 打开余额弹窗
const handleOpenList = (row?: any) => {
  logList.value = row.amount_details;
  listShow.value = true;
}

// 关闭弹窗
const handleCloseList = () => {
  listShow.value = false;
}

const date = ref([]);

const queryParams = reactive<monthlyBillPageQuery>({
  page: 1,
  ps: 10,
  s_water_meter_code: "",
  meter_reader_id: "",
  s_meter_reader_name: "",
  month: "",
  settle_status: "",
  valid_status: "",
  created_at_gte: "",
  created_at_lte: ""
});

const dialog = reactive({
  visible: false,
  title: "新增用户",
});

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  if (date.value.length > 0) {
    queryParams.created_at_gte = date.value[0] / 1000;
    queryParams.created_at_lte = date.value[1] / 1000;
  }
  monthlyBillAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  date.value = [];
  queryParams.created_at_gte = "";
  queryParams.created_at_lte = "";
  queryParams.page = 1;
  handleQuery();
}


/**
 * 删除片区
 *
 * @param id  片区ID
 */
function handleWaterMeterBill(id?: number) {

  ElMessageBox.confirm("确认作废吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      monthlyBillAPI.waterMeterBill({ id })
        .then(() => {
          ElMessage.success("操作成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消操作");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.card :deep(.el-table__row) {
  height: 40px;
  /* 设置每行的固定高度为40px */
}

.card :deep(th),
.card :deep(td) {
  border-color: black;
}

.card :deep(td:nth-child(1)),
.card :deep(td:nth-child(2)) {
  border-color: transparent !important;
}

.card :deep(tr:nth-child(2) th:nth-child(1)),
.card :deep(tr:nth-child(2) th:nth-child(2)) {
  border-color: transparent !important;
}

.card :deep(.el-table thead.is-group th.el-table__cell) {
  border-bottom: 1px solid black;
  background-color: #fff;
  border-color: black;
  font-weight: normal;
  color: #616266 !important;
}

.card :deep(td.el-table__cell) {
  border-bottom: 1px solid black;
}


.card :deep(.el-table--border:after),
.card :deep(.el-table__inner-wrapper:after),
.card :deep(.el-table--border:before),
.card :deep(.el-table__inner-wrapper:before),
.card :deep(.el-table__border-left-patch) {
  background-color: black;
}

.card {
  width: 860px;
  height: 560px;
}

.imageUrl {
  position: absolute;
  left: -1000%;
}

.shoubox {
  position: relative;
  padding-right: 30px;
}

.text-box {
  position: absolute;
  right: 2px;
  width: 25px;
  /* padding-top: 50px; */
  top: 38px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.reamck {
  border: 1px solid black;
  border-top: 0 none;
  overflow: hidden;
}

.reamck-text {
  padding: 5px;
  text-align: center;
  width: 60px;
  box-sizing: border-box;
  float: left;
}

.card :deep(.el-input__inner) {
  height: 25px;
}

.card :deep(.el-input__wrapper) {
  box-shadow: none !important;
}

.card :deep(.el-el-textarea__inner) {
  box-shadow: none !important;
}

.cha {
  display: flex;
  justify-content: center;
  width: 18px;
  height: 18px;
  border: 1px solid black;
  line-height: 10px;
  border-radius: 50%;
  font-size: 26px;
  font-weight: 300;
  box-sizing: border-box;
}

.input-box {
  float: left;
  border-left: 1px solid black;
  width: calc(100% - 60px);
}

.input-box :deep(.el-textarea__inner) {
  all: unset;
  /* 这个可以移除元素的所有样式 */
  box-sizing: border-box;
  /* 保证框架大小一致 */
  width: 100%;
  /* 你可以自定义宽度 */
  height: 28px;
  /* 同样可以自定义高度 */
  padding: 5px;
}

.select-box {
  position: relative;
}

.select {
  position: absolute;
  width: 30px;
  height: 30px;
  background: white;
  right: 0px;
}
</style>
